<script setup lang="ts">
import {SubjectsForm, SubjectsQuery} from "@/api/subjects/types";
import moment from "moment"

/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "Bill",
  inheritAttrs: false,
});
import { UploadFile, ElLoading } from "element-plus";
import lodash from 'lodash-es'
import {
  getBillPage,
  importBill
} from "@/api/bill";

import {findAll} from "@/api/accessory";

import { BillQuery, BillPageVO } from "@/api/bill/types";
import {AccessoryList} from "@/api/accessory/types";
import {getSubjectsList} from "@/api/subjects";
import {listAll} from "@/api/store";
import {StoreForm} from "@/api/store/types";

const queryFormRef = ref(ElForm); // 查询表单

const loading = ref(false);
const ids = ref([]);
const accessoryList = reactive<AccessoryList>({
  value: []
});
const total = ref(0);
const monthList = ref<[]>([])
const subjectList = ref<SubjectsForm[]>();
const storeList = ref<StoreForm[]>();
const tableHeight = ref(150)

const subjectQueryParams = reactive<SubjectsQuery>({
	pageNum: 1,
	pageSize: 50,
});

const queryParams = reactive<BillQuery>({
  pageNum: 1,
  pageSize: 20,
});
const billList = ref<BillPageVO[]>();

const importDialog = reactive<DialogOption>({
  title: "标准账单导入",
  visible: false,
});

/**
 * 导入选择的平台
 */
const importPlatForm = ref<string>();
const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const showMore = ref(false)


/**
 * 获取所有店铺
 */
function getAllStore() {
	listAll().then((response) => {
		storeList.value = []
		const group_store = lodash.groupBy(response.data, 'storeKeyName');
		for (let key in group_store) {
			storeList.value.push({'label': key, 'options': group_store[key]})
		}
	})
}

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
	if (lodash.size(monthList.value) > 0){
		lodash.set(queryParams, 'startMonth', monthList.value[0])
		lodash.set(queryParams, 'endMonth', monthList.value[1])
	}
  getBillPage(queryParams)
    .then(({ data }) => {
	  billList.value = data.list;
	  if (billList.value.length > 0) {
	    for (const bill of billList.value) {
	      const accessory = lodash.get(bill, 'accessory')
	      if (accessory !== null && accessory !== undefined) {
	        for (let key of Object.keys(accessory)) {
	          lodash.set(bill, key, lodash.get(accessory, key))
            }
          }
          const otherAccessory = lodash.get(bill, 'otherAccessory')
          if (otherAccessory !== null && otherAccessory !== undefined) {
            for (let key of Object.keys(otherAccessory)) {
              lodash.set(bill, '对方_'+key, lodash.get(otherAccessory, key))
            }
          }
        }
      }
      total.value = data.total;
			getHeight()
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

/** 打开导入弹窗 */
async function openImportDialog() {
  importPlatForm.value = undefined
  importDialog.visible = true;
}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: UploadFile) {
	if (file.size !== undefined) {
		if (file.size > 20*1024*1024) {
			ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			return false
		}
	}
  if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
    ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
    excelFile.value = undefined;
    excelFilelist.value = [];
    return false;
  }
  excelFile.value = file.raw;
}


/**  关闭导入弹窗 */
function closeImportDialog() {
  importDialog.visible = false;
  excelFile.value = undefined;
  excelFilelist.value = [];
}

function getAllAccessory(){
  accessoryList.value = []
  findAll().then((response) => {
    if (response.data !== null && response.data.length > 0) {
      const head = lodash.head(response.data)
      for (const key of Object.keys(head)) {
        if (key.includes('Name') && lodash.get(head, key) !== null && lodash.get(head, key) !== undefined && lodash.get(head, key) !== '') {
          accessoryList.value.push(lodash.get(head, key))
        }
      }
    }
  })
}

/**
 * 获取科目列表
 */
function getSubjectsListApi(keyword?: string){
	subjectQueryParams.keywords = keyword
  getSubjectsList(subjectQueryParams).then((response) => {
    subjectList.value = response.data;
  });
}

const remoteMethod = (query: string) => {
	getSubjectsListApi(query)
}

function getHeight() {
	if (showMore.value) {
			if (billList.value && billList.value.length > 0) {
				tableHeight.value = 540
			} else {
				tableHeight.value = 150
			}
	}else{
		if (billList.value && billList.value.length > 0) {
			tableHeight.value = 640
		}else{
			tableHeight.value = 150
		}
	}
}

function showMoreHandle() {
	showMore.value = !showMore.value
	getHeight()
}

onMounted(() => {
	let now = new Date()
	let month = now.getMonth()
	let nowMonth;
	if (month < 9){
		nowMonth = now.getFullYear() + '0' + (now.getMonth() + 1) + ''
	}	else {
		nowMonth = now.getFullYear() + '' + (now.getMonth() + 1) + ''
	}
	monthList.value = [nowMonth, nowMonth]
  handleQuery(); // 初始化标准账单配置列表数据
  getAllAccessory()
  getSubjectsListApi()
	getAllStore()
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col>
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="账单日期">
							<el-date-picker
									style="width: 200px"
									v-model="monthList"
									type="monthrange"
									range-separator="至"
									start-placeholder="开始月份"
									end-placeholder="结束月份"
									value-format="YYYYMM"
									:clearable="false"
							/>
            </el-form-item>
						<el-form-item label="电商平台店铺名称" prop="thirdSourceCode">
							<el-select class="yz-el-select" v-model="queryParams.thirdSourceCode" filterable clearable placeholder="请选择店铺">
								<el-option-group
									v-for="group in storeList"
									:key="group.label"
									:label="group.label"
								>
									<el-option
										v-for="item in group.options"
										:key="item.id"
										:label="item.innerSystemStoreName"
										:value="item.commercePlatformStoreCode"
									/>
								</el-option-group>
							</el-select>
						</el-form-item>
						<el-form-item label="记账状态" prop="status">
							<el-select class="yz-el-select" v-model="queryParams.status" placeholder="请选择记账状态" clearable>
								<el-option label="未入账" value="未入账" />
								<el-option label="已入账" value="已入账" />
							</el-select>
						</el-form-item>
						<el-form-item v-if="showMore" label="统一账单ID" prop="keywords">
							<el-input
									v-model="queryParams.keywords"
									placeholder="请输入统一账单ID"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
						<el-form-item label="原始账单ID" prop="linkNo">
							<el-input
									v-model="queryParams.linkNo"
									placeholder="请输入原始账单ID"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
						<el-form-item v-if="showMore" label="汇总ID" prop="summaryId">
							<el-input
									v-model="queryParams.summaryId"
									placeholder="请输入汇总ID"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
						<el-form-item v-if="showMore" label="电商平台账单项目" prop="originalBillProject">
							<el-input
									v-model="queryParams.originalBillProject"
									placeholder="请输入电商平台账单项目"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
						<el-form-item v-if="showMore" label="记账项目" prop="billProject">
							<el-input
									v-model="queryParams.billProject"
									placeholder="请输入记账项目"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
						<el-form-item v-if="showMore" label="末级科目编码" prop="lastCode">
							<el-select class="yz-el-select" v-model="queryParams.lastCode" placeholder="请输入末级科目编码" clearable filterable remote :remote-method="remoteMethod">
								<el-option
										v-for="item in subjectList"
										:key="item.lastCode"
										:label="item.lastCode"
										:value="item.lastCode"
								/>
							</el-select>
						</el-form-item>
						<el-form-item v-if="showMore" label="对账平台电商平台名称" prop="commercePlatformStoreName">
							<el-input
									v-model="queryParams.commercePlatformStoreName"
									placeholder="请输入对账平台电商平台名称"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
						<el-form-item v-if="showMore" label="结算单类型" prop="settlementType">
							<el-input
									v-model="queryParams.settlementType"
									placeholder="请输入结算单类型"
									clearable
									style="width: 200px"
									@keyup.enter="handleQuery"
							/>
						</el-form-item>
            <el-form-item>
              <el-button type="primary" @click="resetQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
							<el-button type="primary" @click="showMoreHandle" >{{showMore ? '隐藏更多' : '更多查询'}}</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <el-table
            size="small"
            :height="tableHeight"
            :header-row-style="{color: 'dimgray'}"
            v-loading="loading"
            :data="billList"
						border
          >
            <el-table-column
              label="对账系统平台名称"
              width="80"
              align="center" show-overflow-tooltip
              prop="billSystemPlatformName"
            />
            <el-table-column
              label="电商平台店铺名称"
              width="80"
              align="center" show-overflow-tooltip
              prop="commercePlatformStoreName"
            />
						<el-table-column
								label="会计期间"
								align="center" show-overflow-tooltip
								prop="sysBillDate"
								width="80"
						/>
            <el-table-column
              label="结算单类型"
              align="center" show-overflow-tooltip
              prop="settlementType"
              width="80"
            />
						<el-table-column
								label="记账状态"
								align="center" show-overflow-tooltip
								prop="status"
								width="80"
						/>
            <el-table-column
              label="原始账单ID"
              align="center" show-overflow-tooltip
              prop="linkNo"
              width="80"
            />
            <el-table-column
              label="统一账单ID"
              align="center" show-overflow-tooltip
              prop="sysBillId"
              width="80"
            />
            <el-table-column
              label="汇总ID"
              align="center" show-overflow-tooltip
              prop="summaryId"
              width="80"
            />
            <el-table-column
              label="业务日期"
              align="center" show-overflow-tooltip
              prop="businessDate"
              width="140"
            />
						<el-table-column
								label="出账日期"
								align="center" show-overflow-tooltip
								prop="billDate"
								width="100"
						/>
            <el-table-column
              label="电商平台账单项目"
              align="center" show-overflow-tooltip
              prop="originalBillProject"
              width="80"
            />
						<el-table-column
								label="发生方借贷方向"
								align="center" show-overflow-tooltip
								prop="borrowing"
								width="80"
						/>
						<el-table-column
								label="账单金额"
								align="center" show-overflow-tooltip
								prop="billAmount"
								width="80"
						/>
            <el-table-column
              label="记账项目"
              align="center" show-overflow-tooltip
              prop="billProject"
              width="200"
            />
						<el-table-column
								label="一级科目编码"
								align="center" show-overflow-tooltip
								prop="firstCode"
								width="80"
						/>
						<el-table-column
								label="一级科目名称"
								align="center" show-overflow-tooltip
								prop="firstName"
								width="80"
						/>
						<el-table-column
								label="末级科目编码"
								align="center" show-overflow-tooltip
								prop="lastCode"
								width="80"
						/>
						<el-table-column
								label="末级科目名称"
								align="center" show-overflow-tooltip
								prop="lastName"
								width="80"
						/>
            <el-table-column
              label="入账主体"
              align="center" show-overflow-tooltip
              prop="companyCode"
              width="80"
            />
            <el-table-column
              label="是否分摊"
              align="center" show-overflow-tooltip
              prop="apportionment"
              width="80"
            />
            <el-table-column
              label="票前票后"
              align="center" show-overflow-tooltip
              prop="invoice"
              width="80"
            />
            <el-table-column
              label="稽核标识"
              align="center" show-overflow-tooltip
              prop="audit"
              width="80"
            />
            <el-table-column
              label="是否参与记账"
              align="center" show-overflow-tooltip
              prop="accounting"
              width="80"
            />
            <el-table-column
              label="供应商名称"
              align="center" show-overflow-tooltip
              prop="carrier"
              width="80"
            />
            <el-table-column
              label="税额"
              align="center" show-overflow-tooltip
              prop="taxAmount"
              width="80"
            />
						<el-table-column
								v-for="accessory in accessoryList.value"
								:label="accessory"
								align="center" show-overflow-tooltip
								:prop="accessory"
								width="80"
						/>
            <el-table-column label="对方">
              <el-table-column
                      label="一级科目编码"
                      align="center" show-overflow-tooltip
                      prop="otherFirstCode"
                      width="80"
              />
              <el-table-column
                      label="一级科目名称"
                      align="center" show-overflow-tooltip
                      prop="otherFirstName"
                      width="80"
              />
              <el-table-column
                      label="末级科目编码"
                      align="center" show-overflow-tooltip
                      prop="otherLastCode"
                      width="80"
              />
              <el-table-column
                      label="末级科目名称"
                      align="center" show-overflow-tooltip
                      prop="otherLastName"
                      width="80"
              />
              <el-table-column
                      label="借贷方向"
                      align="center" show-overflow-tooltip
                      prop="otherBorrowing"
                      width="80"
              />
							<el-table-column
									label="账单金额"
									align="center" show-overflow-tooltip
									prop="otherBillAmount"
									width="80"
							/>
              <el-table-column
                      v-for="accessory in accessoryList.value"
                      :label="accessory"
                      align="center" show-overflow-tooltip
                      :prop="'对方_'+accessory"
                      width="80"
              />
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>
